package logger;

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;

/**
 *
 * @author BDSHADOW
 */
public class ConcurentFileWriter {
    private FileChannel channel;
    private FileOutputStream stream;
    private PrintWriter writer;
    
    public ConcurentFileWriter(File file, PrintWriter writer) throws FileNotFoundException {
        this.stream = new FileOutputStream(file);
        this.channel = stream.getChannel();
        this.writer = writer;
    }
    
    public ConcurentFileWriter(File file, PrintWriter writer, boolean append) throws FileNotFoundException {
        this.writer = writer;
        this.stream = new FileOutputStream(file, append);
        this.channel = stream.getChannel();
    }
    
    public void write(CharBuffer buffer) throws IOException {
        FileLock lock = channel.tryLock();
        while (lock == null) {
            try {
                lock = channel.tryLock();
            } catch (OverlappingFileLockException e) {
                // File is already locked in this thread or virtual machine
            }    
        }
        writer.println(buffer.toString());
        lock.release();
    }    
}
